package com.heima.article.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("test")
public class TestController {


    @Autowired
    private Configuration configuration;

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private MinIOService minIOService;

    @GetMapping("/html/{id}")
    public ResponseResult createHtml(@PathVariable("id") Long id) throws Exception {
        // 获取模板
        Template template = configuration.getTemplate("article.ftl");
        // 拼接数据
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId, id);
        ApArticleContent one = contentService.getOne(query);
        // 合并模板和数据
        Map<String, Object> map = new HashMap<>();
        map.put("content", JSON.parseArray(one.getContent()));
        StringWriter out = new StringWriter();
        template.process(map, out);
        // 上传到minio
        String name = id + ".html";
        InputStream in = new ByteArrayInputStream(out.toString().getBytes());
        String url = minIOService.upload(name, in, "text/html");
        return ResponseResult.okResult(url);
    }
}
